package com.ruoyi.web.controller.workflow;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUtils;

import com.ruoyi.workflow.domain.BusBpmnInfo;
import com.ruoyi.workflow.service.IBusBpmnInfoService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 流程定义信息Controller
 *
 * @author lanmao
 * @date 2022-11-14
 */
@RestController
@RequestMapping("/workflow/bpmnInfo")
public class BusBpmnInfoController extends BaseController
{
    @Autowired
    private IBusBpmnInfoService busBpmnInfoService;

    /**
     * 查询流程定义信息列表
     * /workflow/bpmninfo/list
     */
    @PreAuthorize("@ss.hasPermi('system:bpmnInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusBpmnInfo busBpmnInfo)
    {
        startPage();
        List<BusBpmnInfo> list = busBpmnInfoService.selectBusBpmnInfoList(busBpmnInfo);
        return getDataTable(list);
    }

    /**
     * 删除流程定义信息
     */
    @PreAuthorize("@ss.hasPermi('system:bpmnInfo:remove')")
    @Log(title = "流程定义信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {

        if (ids == null || ids.length ==0){
            return error("请选择你要删除的流程定义");
        }
        return toAjax(busBpmnInfoService.deleteDefinition(ids));
    }

    private static final List<String> FILE_SUBFIX = Arrays.asList("zip","bpmn","xml");

    @PreAuthorize("@ss.hasPermi('business:bpmnInfo:deploy')")
    @Log(title = "流程定义部署", businessType = BusinessType.INSERT)
    @PostMapping("/deploy")
    public AjaxResult deploy(MultipartFile file, BusBpmnInfo bpmnInfo) throws Exception {
        String filename = file.getOriginalFilename();
        String suffix = FileUtils.getSuffix(filename);
        if (!FILE_SUBFIX.contains(suffix)){
            return AjaxResult.error("请上传"+ FILE_SUBFIX + "的文件");
        }
        bpmnInfo.setResource(filename);
        busBpmnInfoService.deploy(bpmnInfo, file.getInputStream());

        return AjaxResult.success("部署成功");
    }

    @PreAuthorize("@ss.hasPermi('business:bpmnInfo:deploy')")

    @GetMapping("/resouces/{id}")
    public void getResouce(@PathVariable Long id,String type,HttpServletResponse resp) throws Exception {
            //  TODO 参数校验非空判断
       InputStream resouces= busBpmnInfoService.getResouceByType(id,type);
        IOUtils.copy(resouces,resp.getOutputStream());
    }


}
